﻿using System;
using System.Data;
using System.Web;
using System.Web.Security;
using NazSoft.Framework.UsersManagement;

namespace App_Code
{
    public class AuthClass
    {
        public AuthClass()
        {

        }

        public static bool IsUserValid(string userId, string password, bool isPresist)
        {

            DataTable dt = UserHelper.GetUserInfo(userId, password);
            bool userValid;

            if (dt.Rows.Count > 0)
                userValid = true;
            else
                userValid = false;

            if (userValid == true)
            {
                int intUserId = Convert.ToInt32(dt.Rows[0].ItemArray[0]);

                //var helperCoEntities = new HelperCoDataContext();

                //var sessionLogs = new tblSessionLog();
                
                //sessionLogs.IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                //sessionLogs.Host_Name = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                //sessionLogs.Start_DateTime = DatetimeUtility.GetCurrentDateTime();
                //sessionLogs.User_Id = intUserId;
                //helperCoEntities.tblSessionLogs.InsertOnSubmit(sessionLogs);
                //helperCoEntities.SubmitChanges();
                HttpContext.Current.Session["SessionId"] = 0;//sessionLogs.Session_Id;
                HttpContext.Current.Session["UserId"] = intUserId;
                    
               // var f = new FormsAuthenticationTicket(userId, isPresist, 120);
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userId, true);

                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                if (ticket != null)
                {
                    var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration.Add(new TimeSpan(1,1,1)), true, userId);
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                }

                HttpContext.Current.Response.Cookies.Add(authCookie);
            }

            return userValid;
        }


    }
}
